from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from myapp.models import User,Course,Flow
from myapp.myser import CourseSer

from django.utils.deprecation import MiddlewareMixin

from django.http import QueryDict


#类视图调用
from django.utils.decorators import method_decorator

#事务操作
from django.db import transaction

import hmac
import base64
from hashlib import sha256
import urllib


user = 0b111

permission = 0b001


from myapp.test_queue import MyQueue


myq = MyQueue()

class GetJob(APIView):


	def get(self,request):

		#出队
		myjob = myq.pop()

		return Response(myjob)



#修改用户名(微信号)
class UpdateUserName(APIView):


	def get(self,request):

		#获取id
		uid = request.GET.get('uid',None)
		#用户名
		username = request.GET.get('username',None)

		#入队

		myq.push((uid,username))

		return Response({"msg":" 正在审核中，请耐心等待 "})



#获取关注状态
class GetFlow(APIView):


	def get(self,request):


		#获取课程id
		id = request.GET.get('id',None)
		uid = request.GET.get('uid',None)

		flow = Flow.objects.filter(uid=uid,course_id=id).first()

		if flow:
			return Response({'state':'true'})
		else:
			return Response({'state':'false'})



#课程详情页
class CourseDetail(APIView):


	def get(self,request):

		#连接redis

		r = redis.Redis()


		#获取课程id
		id = request.GET.get('id',None)

		#判断逻辑
		if r.get(str(id)):

			#缓存中存在

			data = eval(str(r.get(id),'utf-8'))

		else:

			#缓存中不存在，读库
			course = Course.objects.get(pk=id)

			course_ser = CourseSer(course)

			data = course_ser.data

			#设置缓存
			r.set(str(id),str(course_ser.data))

			print(r.get(str(id)))


		return Response(data)



#课程列表页
class CourseList(APIView):

	def get(self,request):

		#当前页
		page = request.GET.get('page',1)

		#每页展示条数
		size = request.GET.get('size',1)

		#连接redis
		r = redis.Redis()

		#总条数
		count = Course.objects.count()

		#判断逻辑
		if r.get("list"+str(page)):

			#直接读取缓存

			data = eval(str(r.get("list"+str(page)),'utf-8'))

		else:

			#读库然后设置缓存

			#开始位置
			data_start = (int(page)-1) * int(size)

			#结束位置
			data_end = int(page) * int(size)

			#查询
			courselist = Course.objects.all()[data_start:data_end]

			#序列化
			courselist_ser = CourseSer(courselist,many=True)


			data = courselist_ser.data

			#转换操作

			#取值
			list_value = []
			for value in data[0].values():
				list_value.append(value)

			#取key
			list_key = []
			for key in data[0].keys():
				list_key.append(key)

			print(list_key)
			print(list_value)

			zip_dict = zip(list_key,list_value)
			my_dict = dict(zip_dict)
			print(my_dict)


			#设置缓存
			r.set("list"+str(page),str(my_dict))

		return Response({'total':count,'data':data})






#装饰器
def my_decorator(func):

	def wrapper(request,*args,**kwargs):

		print('装饰器被调用')

		if user & permission:

			return func(request,*args,**kwargs)
		else:
			return HttpResponse('您没有权限')

	return wrapper

#上传头像
@my_decorator
def upload_img(request):

	return HttpResponse('上传成功')


def dictfetchall(cursor):

	desc = cursor.description

	return [

	dict(zip([col[0] for col in desc ],row))

	for row in cursor.fetchall()

	]


class AddCourse(APIView):

	def get(self,request):

		title = request.GET.get('title',None)
		desc = request.GET.get('desc',None)
		price = request.GET.get('price',None)
		video = request.GET.get('video',None)
		cid = request.GET.get('cid',None)


		#入库操作
		course = Course(title=title,desc=desc,price=price,video=video,cid=cid)

		#保存
		course.save()


		return Response({'code':200,'message':'提交课程成功'})






#构造课程分类层级关系(树)
def get_tree(data):

	lists = []
	tree = {}

	for item in data:
		tree[item['id']] = item

	for i in data:
		if not i['pid']:
			lists.append(tree[i['id']])
		else:
			parent_id = i['pid']
			if "children" not in tree[parent_id]:
				tree[parent_id]["children"] = []
			tree[parent_id]['children'].append(tree[i['id']])

	return lists

#获取课程分类
def get_cate(request):

	#建立查询游标
	cursor = connection.cursor()
	#执行sql
	cursor.execute('SELECT * from cate')
	#获取结果集
	#res = cursor.fetchall()
	res = dictfetchall(cursor)

	#强转
	res = get_tree(res)

	return HttpResponse(json.dumps(res,indent=4,ensure_ascii=False),content_type='application/json')



#获取某个用户的权限
class GetUserAccess(View):

	def get(self,request):


		uid = request.GET.get('uid',None)

		#建立查询游标
		cursor = connection.cursor()
		#执行sql
		cursor.execute('SELECT a.username,c.node_name,c.id from user a left join access b on a.id = b.uid left join node c on b.node_id = c.id where a.id = %s;' % uid)
		#获取结果集
		#res = cursor.fetchall()
		res = dictfetchall(cursor)

		return HttpResponse(json.dumps(res,indent=4,ensure_ascii=False),content_type='application/json')


#定义验证码类
class MyCode(View):

	#内置类方法
	def get_random_color(self):

		R = random.randrange(255)
		G = random.randrange(255)
		B = random.randrange(255)

		return (R,G,B)

	def get(self,request):

		#定义画布
		img_size = (120,50)

		#定义图像对象
		image = Image.new("RGB",img_size,'white')
		#定义画笔
		draw = ImageDraw.Draw(image,'RGB')
		#定义字符串
		source = '0123456789abcdefg'
		#定义容器
		code_str = ""
		for i in range(4):
			#获取字符颜色
			text_color = self.get_random_color()
			#获取随机字符
			tmp_num = random.randrange(len(source))
			random_str = source[tmp_num]
			code_str += random_str
			draw.text((10+30*i,20),random_str,text_color)

		buf = io.BytesIO()
		image.save(buf,'png')

		#保存验证码
		request.session['code'] = code_str

		r = redis.Redis()

		r.set('code',code_str)

		return HttpResponse(buf.getvalue(),'image/png')





def make_password(mypass):

	#生成对象
	md5 = hashlib.md5()
	#定义加密对象
	sign_str = mypass
	#转码
	sign_utf8 = str(sign_str).encode(encoding="utf-8")
	#加密
	md5.update(sign_utf8)
	#生成密文
	md5_server = md5.hexdigest()

	return md5_server


#登录接口
class Login(APIView):

	def post(self,request):

		username = request.POST.get("username",None)
		phone = request.POST.get("username",None)
		password = request.POST.get("password",None)


		#获取验证码
		code = request.session.get('code',None)
		r = redis.Redis()
		code = r.get("code")

		print(code)

		#判断
		if username == None:

			user = User.objects.filter(phone=phone,password=password).first()
		else:
			user = User.objects.filter(username=username,password=password).first()

		if user:
			#创建jwt
			encode_jwt = jwt.encode({'uid':user.id,'username':user.username},'123',algorithm='HS256')
			encode_str = encode_jwt


			return Response({'code':200,'message':'登录成功','username':user.username,'token':encode_str})
		else:
			return Response({'code:':405,'message':'您的用户名或者密码错误'})

#用户注册
class Register(APIView):

	def get(self,request):

		#接收参数
		username = request.GET.get("username",None)
		password = request.GET.get("password",None)

		#排重
		#user = User.objects.filter(username=username).first() #.get(username=username)

		# if user:
		# 	res = {}
		# 	res['code'] = 405
		# 	res['message'] = '用户已经存在'

		# 	return Response(res)

		#入库 捕获异常
		try:
			user = User(username=username,password=make_password(password))
			user.save()
			return Response({'code':200,'message':'注册成功'})
		except Exception as e:
			print(str(e))
			return Response({'code':405,'message':'用户已存在'})

		